package com.iyao_app.mvp.info;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.backends.pipeline.PipelineDraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.iyao_app.R;
import com.iyao_app.adapter.LiuyanAdapter;
import com.iyao_app.adapter.PersonInfoAdapter;
import com.iyao_app.adapter.WhoLookMeAdapter;
import com.iyao_app.base.BaseActivityWithHead;
import com.iyao_app.entry.CallList;
import com.iyao_app.entry.HomeData;
import com.iyao_app.entry.Other;
import com.iyao_app.entry.PreviewData;
import com.iyao_app.entry.ResultModel;
import com.iyao_app.entry.User;
import com.iyao_app.entry.Visit;
import com.iyao_app.entry.VisitData;
import com.iyao_app.http.NetCallBack;
import com.iyao_app.http.NetUtils;
import com.iyao_app.im.activity.AttentionActivity;
import com.iyao_app.im.activity.PersonalDataActivity;
import com.iyao_app.im.activity.SystemSettingsActivity;
import com.iyao_app.mvp.other.OtherHomeActivity;
import com.iyao_app.mvp.preview.ImageViewPagerActivity;
import com.iyao_app.mvp.signlist.CustomListActivity;
import com.iyao_app.mvp.signlist.SignMapListActivity;
import com.iyao_app.util.Contants;
import com.iyao_app.util.DbUtil;
import com.iyao_app.util.MessageEvent;
import com.iyao_app.util.ResourcesUtils;
import com.iyao_app.util.SpaceItemDecoration_;
import com.iyao_app.util.TimeFormat;
import com.iyaowoqu.base_library.util.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者 :  胡家兵
 * 时间 :  2017/11/30.
 */

public class PersonInfoActivity extends BaseActivityWithHead {


    @BindView(R.id.tv_money)
    TextView mTvMoney;
    @BindView(R.id.tv_id)
    TextView mTvId;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_location)
    TextView mTvLocation;
    @BindView(R.id.rv_horizontal)
    RecyclerView mRvHorizontal;
    @BindView(R.id.tv_who_see_me)
    TextView mTvWhoSeeMe;
    @BindView(R.id.rv_who_see_me)
    RecyclerView mRvWhoSeeMe;
    @BindView(R.id.iv_more)
    ImageView mIvMore;
    @BindView(R.id.lin_1)
    LinearLayout mLin1;
    @BindView(R.id.tv_who_call_me)
    TextView mTvWhoCallMe;
    @BindView(R.id.tv_more)
    TextView mTvMore;
    @BindView(R.id.lin_2)
    LinearLayout mLin2;
    @BindView(R.id.rv_more)
    RecyclerView mRvMore;
    @BindView(R.id.sdv_head)
    SimpleDraweeView mSdvHead;
    @BindView(R.id.nest_scroll)
    NestedScrollView mNestScroll;
    @BindView(R.id.main_content)
    CoordinatorLayout mMainContent;
    @BindView(R.id.iv_sex)
    ImageView mIvSex;
    @BindView(R.id.tv_tui_jian)
    TextView mTvTuiJian;
    @BindView(R.id.lin7)
    LinearLayout mLin7;
    @BindView(R.id.rl_no_see)
    LinearLayout mRlNoSee;
    @BindView(R.id.lin_who_see_me)
    LinearLayout mLinWhoSeeMe;
    @BindView(R.id.rl_more)
    LinearLayout mRlMore;

    private LiuyanAdapter adapter;
    private PersonInfoAdapter pictureAdapter;
    private User user;
    private WhoLookMeAdapter whoLookMeAdapter;
    private List<String> fileUrlList;
    private Other other;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);
        ButterKnife.bind(this);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventUpdate(MessageEvent event) {
        if (event.getState() == MessageEvent.USER_INFO_REFUSH)
            update();
    }

    private void initData() {

        setNextImage(R.mipmap.btn_shezhi);
        onNextClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(PersonInfoActivity.this, SystemSettingsActivity.class));
            }
        });

        mRvMore.setNestedScrollingEnabled(false);
        mRvMore.setFocusable(false);
        mRvHorizontal.setFocusable(false);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);


        pictureAdapter = new PersonInfoAdapter(null);
        mRvHorizontal.setAdapter(pictureAdapter);
        mRvHorizontal.addItemDecoration(new SpaceItemDecoration_((int) ResourcesUtils.getDimension(R.dimen.x20)));
        mRvHorizontal.setLayoutManager(linearLayoutManager);


        adapter = new LiuyanAdapter(null);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRvMore.setLayoutManager(manager);
        mRvMore.setAdapter(adapter);
        adapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        adapter.isFirstOnly(false);
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.sdv_head) {
                    CallList item = (CallList) adapter.getItem(position);
                    Intent intent = new Intent(PersonInfoActivity.this, OtherHomeActivity.class);
                    intent.putExtra(Contants.TYPE, String.valueOf(item.sayHelloFromUserId));
                    startActivity(intent);
                }
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        whoLookMeAdapter = new WhoLookMeAdapter(this, null);
        mRvWhoSeeMe.addItemDecoration(new SpaceItemDecoration_((int) ResourcesUtils.getDimension(R.dimen.x_10)));
        mRvWhoSeeMe.setLayoutManager(layoutManager);
        mRvWhoSeeMe.setAdapter(whoLookMeAdapter);
        update();
        getData();

        pictureAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                String item = (String) adapter.getItem(position);
                if ("mipmap".equals(item)) {//视觉印象
                    Intent intent = new Intent(PersonInfoActivity.this, VisionImpressionActivity.class);
                    startActivity(intent);
                } else {//预览
                    List<String> stringList = new ArrayList<>();
                    for (String s : pictureAdapter.getData()) {
                        if (!"mipmap".equals(s)) {
                            stringList.add(s);
                        }
                    }
                    PreviewData previewData = new PreviewData();
                    previewData.image = stringList;
                    previewData.position = position;
                    Intent intent = new Intent(PersonInfoActivity.this, ImageViewPagerActivity.class);
                    intent.putExtra(Contants.CLASS_TYPE, previewData);
                    startActivity(intent);
                }
            }
        });
    }

    private void update() {
        user = DbUtil.getUser();
        if (user != null) {
            mTvId.setText(user.id);
            mTvTuiJian.setText(user.invitationCode);


            if (!TextUtils.isEmpty(user.avatarUrl)) {
                try {
                    Uri uri = Uri.parse(user.avatarUrl);
                    ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                            .setResizeOptions(new ResizeOptions(200, 200))
                            .build();
                    PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                            .setOldController(mSdvHead.getController())
                            .setImageRequest(request)
                            .build();
                    mSdvHead.setController(controller);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                mTvName.setText(user.nickname);
                if (user.sex == 1) {
                    mIvSex.setImageResource(R.mipmap.ic_boy);
                } else {
                    mIvSex.setImageResource(R.mipmap.ic_girl);
                }
                String s = null;
                int age = 0;
                if (user.birthday != 0) {
                    age = TimeFormat.getAgeFromBirthTime(user.birthday);
                }
                if (TextUtils.isEmpty(user.district) && TextUtils.isEmpty(user.city)) {
                    s = String.format("%d，%s", age, getString(R.string.from_huo_xing));
                } else {
                    s = String.format("%d，%s %s", age, user.district, user.city);
                }
                mTvLocation.setText(s);
            }
            String visionImpression = user.visionImpression;
            pictureAdapter.getData().clear();
            pictureAdapter.notifyDataSetChanged();
            pictureAdapter.addData(user.avatarUrl);
            if (!TextUtils.isEmpty(visionImpression)) {
                List<String> strings = JSON.parseArray(visionImpression, String.class);
                if (strings != null && strings.size() > 0)
                    pictureAdapter.notifyItemRangeRemoved(1, pictureAdapter.getData().size() - 1);
                pictureAdapter.addData(strings);
            }
            if (pictureAdapter.getData().size() <= 6) {
                pictureAdapter.addData("mipmap");
            }
        }
    }


    @OnClick({R.id.iv_qian_dao, R.id.iv_gu_shi, R.id.iv_guan_zhu, R.id.iv_more, R.id.tv_more, R.id.sdv_head})
    public void onViewClicked(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.iv_qian_dao:

                intent = new Intent(this, SignMapListActivity.class);

                intent.putExtra(Contants.TYPE, user.id);

                startActivity(intent);
                break;
            case R.id.iv_gu_shi:
                intent = new Intent(this, CustomListActivity.class);
                intent.putExtra(Contants.TYPE, user.id);
                startActivity(intent);
                break;
            case R.id.iv_guan_zhu:
                intent = new Intent(this, AttentionActivity.class);
                intent.putExtra(Contants.TYPE, 0);
                startActivity(intent);

                break;
            case R.id.iv_more:
                intent = new Intent(PersonInfoActivity.this, WhoSeeMeActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_more:
                intent = new Intent(PersonInfoActivity.this, WhoCallMeActivity.class);
                intent.putExtra(Contants.TYPE, user.id);
                intent.putExtra(Contants.CLASS_TYPE, 1);
                startActivity(intent);
                break;
            case R.id.sdv_head:
                intent = new Intent(this, PersonalDataActivity.class);
                intent.putExtra(Contants.TYPE, other);
                startActivity(intent);
                break;
        }
    }

    private void getData() {
        if (user == null) {
            return;
        }
        NetUtils.getInstance().getOtherInfo(user.id, user.id, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model == null) return;
                    other = model.getModel();
                    if (other != null) {
                        callList();
                        getVisitor();
                        if (!TextUtils.isEmpty(other.avatarUrl) && other.avatarUrl.startsWith("http")) {
                            user.avatarUrl = other.avatarUrl;
                            try {
                                Uri uri = Uri.parse(other.avatarUrl);
                                ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                                        .setResizeOptions(new ResizeOptions(200, 200))
                                        .build();
                                PipelineDraweeController controller = (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
                                        .setOldController(mSdvHead.getController())
                                        .setImageRequest(request)
                                        .build();
                                mSdvHead.setController(controller);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            other.avatarUrl = user.avatarUrl;
                        }
                        int age = 0;
                        if (other.birthday != 0) {
                            user.birthday = other.birthday;
                            age = TimeFormat.getAgeFromBirthTime(other.birthday);
                            LogUtil.e("other.birthday" + other.birthday + "===" + age);
                        }
                        user.nickname = other.nickname;
                        mTvName.setText(other.nickname);
                        user.sex = other.sex;
                        if (other.sex == 1) {
                            mIvSex.setImageResource(R.mipmap.ic_boy);
                        } else {
                            mIvSex.setImageResource(R.mipmap.ic_girl);
                        }
                        mTvMoney.setText(String.valueOf(other.goldCount));
                        String s = null;
                        user.district = other.district;
                        user.city = other.city;
                        if (TextUtils.isEmpty(other.district) && TextUtils.isEmpty(other.city)) {
                            s = String.format("%d，%s", age, getString(R.string.from_huo_xing));
                            mTvLocation.setText(s);
                        } else {
                            s = String.format("%d，%s %s", age, other.district, other.city);
                            mTvLocation.setText(s);
                        }
                        fileUrlList = other.fileUrlList;

                        if (fileUrlList != null && fileUrlList.size() > 0) {
                            String jsonString = JSON.toJSONString(fileUrlList, true);
                            LogUtil.e("==jsonString==" + jsonString);
                            user.visionImpression = jsonString;
                        }
                        pictureAdapter.getData().clear();
                        pictureAdapter.notifyDataSetChanged();
                        if (fileUrlList == null || fileUrlList.size() == 0) {
                            if (pictureAdapter.getData().size() == 0) {
                                pictureAdapter.addData(other.avatarUrl);
                                pictureAdapter.addData("mipmap");
                            } else {
                                pictureAdapter.setData(0, other.avatarUrl);
                                pictureAdapter.addData("mipmap");
                            }
                        } else {
                            if (pictureAdapter.getData().size() == 0) {
                                pictureAdapter.addData(other.avatarUrl);
                            } else {
                                pictureAdapter.setData(0, other.avatarUrl);
                            }
                            if (other.fileUrlList.size() >= Contants.MAX_VALUE) {
                                pictureAdapter.addData(other.fileUrlList);
                            } else {
                                pictureAdapter.addData(other.fileUrlList);
                                pictureAdapter.addData("mipmap");
                            }
                        }
                        DbUtil.updateUserInfo(user);
                    }
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, Other.class);
    }

    private void callList() {
        if (user == null) {
            return;
        }
        NetUtils.getInstance().sayHelloList(user.id, 1, 6, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {
                        HomeData homeData = model.getModel();
                        if (homeData != null) {
                            List<CallList> list = homeData.getList();
                            if (list == null || list.size() == 0) {
                                mRlMore.setVisibility(View.VISIBLE);
                                mRvMore.setVisibility(View.GONE);
                                mTvMore.setVisibility(View.GONE);
                            } else {
                                adapter.addData(list);
                                mRlMore.setVisibility(View.GONE);
                                mRvMore.setVisibility(View.VISIBLE);
                                mTvMore.setVisibility(View.VISIBLE);
                            }

                        } else {
                            mTvMore.setVisibility(View.GONE);
                            mRlMore.setVisibility(View.VISIBLE);
                            mRvMore.setVisibility(View.GONE);
                        }
                    }
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, HomeData.class);
    }

    private void getVisitor() {
        if (user == null) {
            return;
        }
        NetUtils.getInstance().getVisitor(user.id, 1, 5, new NetCallBack() {
            @Override
            public void onSuccess(String message, int code, String response, ResultModel model) {
                if (code == Contants.SUCCESS_CODE) {
                    if (model != null) {
                        VisitData visitData = model.getModel();
                        if (visitData != null) {
                            List<Visit> list = visitData.list;
                            if (list == null || list.size() == 0) {
                                mRlNoSee.setVisibility(View.VISIBLE);
                                mLinWhoSeeMe.setVisibility(View.GONE);
                            } else {
                                whoLookMeAdapter.append(list);
                                mRlNoSee.setVisibility(View.GONE);
                                mLinWhoSeeMe.setVisibility(View.VISIBLE);
                            }
                        } else {
                            mRlNoSee.setVisibility(View.VISIBLE);
                            mLinWhoSeeMe.setVisibility(View.GONE);
                        }
                    }
                }
            }

            @Override
            public void onFail(String message, int code) {

            }
        }, VisitData.class);
    }
}
